<script>
import {useArticleApi} from "@/api/homePage";
import {getUserIntegral, GetUserCoupons} from "@/api/homePage";

export default {
  name: "index",
  data() {
    return {
      // 车牌号相关
      carNumber: '',
      showKeyboard: false,
      provinces: ['粤', '京', '津', '冀', '晋', '蒙', '辽', '吉', '黑', '沪', '苏', '浙', '皖', '闽', '赣', '鲁', '豫', '鄂', '湘', '桂', '琼', '渝', '川', '贵', '云', '藏', '陕', '甘', '青', '宁', '新'],
      keyboards: [
        ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'],
        ['Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P'],
        ['A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L'],
        ['Z', 'X', 'C', 'V', 'B', 'N', 'M']
      ],
      inputType: 'province', // province: 省份, number: 字母数字
      maxLength: 8, // 最大输入长度，新能源车牌8位

      // 停车信息
      parkingInfo: null,
      loading: false,

      // 轮播图数据
      bannerList: [],
      currentBanner: 0,
      // 停车场名称列表
      parkingNames: ['香洲港码头停车场', '香洲港码头停车场', '香洲港码头停车场'],
      userPoints: 0,

      // 优惠券相关
      coupons: [],
      selectedCoupon: null,
      displayCoupons: [],
      originalPrice: 0,
      businessId: 214, // 商家ID
    }
  },
  watch: {
    '$i18n.locale'() {
      // 监听语言变化，重新设置导航栏标题
      this.setNavigationTitle();
    }
  },
  computed: {
    // 停车时长（小时和分钟）
    parkingDuration() {
      if (!this.parkingInfo) return { hours: 0, minutes: 0 };

      const start = new Date(this.parkingInfo.entryTime);
      const now = new Date();
      const diff = Math.floor((now - start) / 1000 / 60); // 分钟差

      return {
        hours: Math.floor(diff / 60),
        minutes: diff % 60
      };
    },

    // 应付金额
    payAmount() {
      if (!this.parkingInfo) return 0;

      const { hours } = this.parkingDuration;
      let amount = 0;

      if (hours === 0) {
        amount = 0.01; // 不足1小时按1小时计算
      } else {
        amount = 0.01 + (hours * 0.01);
      }

      this.originalPrice = amount;

      if (this.selectedCoupon) {
        // 强制转换为数字，兜底为0
        const discount = Number(this.selectedCoupon.CouponTemple.FullReduceAmount) || 0;
        amount = Math.max(0, amount - discount);
      }

      // 最终返回也兜底
      return isNaN(amount) ? 0 : amount;
    }
  },
  onLoad() {
    // 设置导航栏标题
    this.setNavigationTitle();
    this.init();
    this.getUserPoints();
    this.getUserCoupons();
  },
  methods: {
    init(){
      useArticleApi({
        ArticleCategoryId: 3605
      }).then(res =>{
        this.bannerList = res.Data.map(item => item.CoverImg)
      })
    },
    // 检查车牌号是否完成
    isCarNumberComplete() {
      // 普通车牌7位，新能源车牌8位
      return this.carNumber.length === 7 || this.carNumber.length === 8;
    },

    // 轮播图切换事件
    bannerChange(index) {
      this.currentBanner = index;
    },

    // 显示车牌键盘
    showCarKeyboard() {
      this.showKeyboard = true;
      if (this.carNumber.length === 0) {
        this.inputType = 'province';
      } else {
        this.inputType = 'number';
      }
    },

    // 隐藏车牌键盘
    hideCarKeyboard() {
      this.showKeyboard = false;
    },

    // 点击省份
    clickProvince(province) {
      if (this.carNumber.length === 0) {
        this.carNumber = province;
        this.inputType = 'number';
      }
    },

    // 点击键盘字符
    clickKey(key) {
      // 新能源车牌8位，普通车牌7位
      if (this.carNumber.length < 8) {
        this.carNumber += key;
      }

      // 输入完成后自动隐藏键盘
      if (this.carNumber.length === 8 || (this.carNumber.length === 7 && !this.isNewEnergyVehicle(this.carNumber))) {
        this.hideCarKeyboard();
        this.queryParkingInfo();
      }
    },

    // 删除输入的字符
    deleteKey() {
      if (this.carNumber.length > 0) {
        this.carNumber = this.carNumber.slice(0, -1);

        // 如果删除到没有字符，切换到省份选择
        if (this.carNumber.length === 0) {
          this.inputType = 'province';
        }
      }
    },

    // 判断是否是新能源车牌
    isNewEnergyVehicle(carNumber) {
      // 简单判断：新能源车牌第3位是字母D/F
      if (carNumber.length >= 3) {
        const thirdChar = carNumber.charAt(2);
        return thirdChar === 'D' || thirdChar === 'F';
      }
      return false;
    },

    // 查询停车信息
    queryParkingInfo() {
      console.log("查询停车信息", this.carNumber);
      if (!this.isCarNumberComplete()) {
        console.log("车牌号未输入完成");
        return;
      }

      this.loading = true;
      console.log("开始加载");

      // 模拟接口请求
      setTimeout(() => {
        // 模拟数据
        this.parkingInfo = {
          carNumber: this.carNumber,
          entryTime: new Date(new Date().getTime() - Math.floor(Math.random() * 5 * 60 * 60 * 1000)), // 随机1-5小时前
          parkingLot: {
            name: this.parkingNames[this.currentBanner]
          },
          status: 'parking' // parking: 停车中, paid: 已支付
        };

        console.log("加载完成", this.parkingInfo);
        this.loading = false;
      }, 1000);
    },

    // 重新输入车牌
    resetCarNumber() {
      this.carNumber = '';
      this.parkingInfo = null;
      this.showKeyboard = true;
      this.inputType = 'province';
    },

    // 去支付
    goPay() {
      if (!this.parkingInfo) return;

      uni.showLoading({
        title: this.$t('parking.index.paymentRedirecting')
      });

      // 模拟跳转支付
      setTimeout(() => {
        uni.hideLoading();

        uni.navigateTo({
          url: `/user_subpages/parking/payment?amount=${this.payAmount}&carNumber=${this.carNumber}`
        });
      }, 1000);
    },
    async getUserPoints() {
      try {
        const res = await getUserIntegral();
        if (res && res.Data !== undefined) {
          this.userPoints = res.Data;
        } else {
          this.userPoints = 0;
        }
      } catch (error) {
        this.userPoints = 0;
      }
    },
    exchangeParkingCoupon() {
      // uni.showToast({ title: '敬请期待', icon: 'none' });
      uni.navigateTo({
        url: '/user_subpages/vip/coupon'
      });
    },
    // 获取用户优惠券
    async getUserCoupons() {
      try {
        const { Data } = await GetUserCoupons({
          Index: 1,
          Size: 100,
          BusinessId: this.businessId,
          CouponStatus: 1
        });
        if (Data && Array.isArray(Data)) {
          this.coupons = Data.filter(coupon => {
            if (!coupon.BusinessIds) return false;
            const businessIds = coupon.BusinessIds.map(id => id);
            return businessIds.includes(this.businessId);
          });
          // 处理显示用的 displayCoupons，保证 amount/min 为数字
          this.displayCoupons = this.coupons.map(coupon => {
            let amount = 0, min = 0, name = '优惠券';
            if (coupon.CouponTemple) {
              amount = Number(coupon.CouponTemple.FullReduceAmount) || 0;
              min = Number(coupon.CouponTemple.MinimumConsumption) || 0;
              name = coupon.CouponTemple.Name ? coupon.CouponTemple.Name : '优惠券';
            }
            return {
              id: coupon.id || coupon.Id,
              amount,
              min,
              name,
              time: this.formatCouponTime(coupon),
              raw: coupon
            };
          });
        } else {
          this.coupons = [];
          this.displayCoupons = [];
        }
      } catch (error) {
        this.coupons = [];
        this.displayCoupons = [];
      }
    },
    selectCoupon(couponObj) {
      if (this.selectedCoupon && this.selectedCoupon.id === couponObj.id) {
        this.selectedCoupon = null;
      } else {
        this.selectedCoupon = couponObj;
      }
    },
    formatCouponTime(coupon) {
      if (!coupon.EffectStartDatetime || !coupon.EffectEndDatetime) return '';
      const start = new Date(coupon.EffectStartDatetime);
      const end = new Date(coupon.EffectEndDatetime);
      const formatDate = (date) => {
        const month = date.getMonth() + 1;
        const day = date.getDate();
        return `${month}月${day}日`;
      };
      return `${formatDate(start)}-${formatDate(end)}`;
    },
    calculateOriginalPrice() {
      if (!this.parkingInfo) return 0;

      const { hours } = this.parkingDuration;
      let amount = 0;

      if (hours === 0) {
        amount = 0.01;
      } else {
        amount = 0.01 + (hours * 0.01);
      }

      return amount;
    },
    // 设置导航栏标题
    setNavigationTitle() {
      uni.setNavigationBarTitle({
        title: this.$t('parking.index.title')
      });
    }
  },
  watch: {
    // 监听停车信息变化，更新原始价格
    parkingInfo: {
      handler(newVal) {
        if (newVal) {
          this.originalPrice = this.calculateOriginalPrice();
        }
      },
      immediate: true
    }
  }
}
</script>

<template>
  <view class="parking-container">
    <!-- 轮播图 -->
    <view class="banner-section">
      <u-swiper
        :list="bannerList"
        keyName="image"
        height="400rpx"
        :autoplay="true"
        :interval="3000"
        @change="bannerChange"
        indicator
        indicatorMode="dot"
      ></u-swiper>
    </view>

    <!-- 合并的积分和车牌输入区域 -->
    <view class="combined-card">
      <!-- 积分和兑换按钮 -->
      <view class="points-card">
        <view class="points-row">
          <view class="points-left">
            <image src="https://wzws.wanshanlundiao.cn/upload/img/20250516/202505161119283990.png"></image>
            {{$t('parking.index.myPoints')}}：<text class="points-value">{{userPoints}}</text>
          </view>
          <view class="points-btn" @click="exchangeParkingCoupon">{{$t('parking.index.exchangeParkingCoupon')}}>></view>
        </view>
      </view>

      <!-- 车牌输入区域 -->
      <view class="car-number-section">
        <view class="car-number-input-grid" @click="showCarKeyboard">
          <view
            v-for="(_, index) in maxLength"
            :key="index"
            class="input-box"
            :class="{ 'active': index === carNumber.length, 'filled': index < carNumber.length, 'new-energy-box': index === maxLength - 1 }"
          >
            <text v-if="index < carNumber.length">{{ carNumber[index] }}</text>
            <view v-else-if="index === carNumber.length" class="cursor"></view>
            <view v-else-if="index === maxLength - 1" class="new-energy-tag">
              <text class="energy-text">新</text>
            </view>
          </view>
        </view>
        <!-- 查询按钮 -->
        <view
          class="query-btn"
          :class="{'active': isCarNumberComplete()}"
          @click="queryParkingInfo"
        >
          {{$t('parking.index.query')}}
        </view>
      </view>
    </view>

    <!-- 停车信息显示区域 -->
    <view class="parking-info-section" v-if="parkingInfo">
      <view class="info-header">
        <view class="car-info">
          <text class="car-number">{{parkingInfo.carNumber}}</text>
          <text class="parking-lot">{{parkingInfo.parkingLot.name}}</text>
        </view>
        <view class="edit-btn" @click="resetCarNumber">{{$t('parking.index.reenter')}}</view>
      </view>

      <view class="info-content">
        <view class="info-item">
          <text class="label">{{$t('parking.index.entryTime')}}</text>
          <text class="value">{{new Date(parkingInfo.entryTime).toLocaleString()}}</text>
        </view>

        <view class="info-item">
          <text class="label">{{$t('parking.index.parkingDuration')}}</text>
          <text class="value">{{$t('parking.index.durationFormat', {hours: parkingDuration.hours, minutes: parkingDuration.minutes})}}</text>
        </view>

        <!-- 优惠券选择区域 -->
        <view class="coupon-section" v-if="coupons.length > 0">
          <view class="coupon-header">
            <text class="label">{{$t('parking.index.coupons')}}</text>
            <view class="coupon-status" v-if="selectedCoupon">
              {{$t('parking.index.discountApplied', {amount: selectedCoupon.CouponTemple.FullReduceAmount})}}
            </view>
            <view class="coupon-status" v-else>
              {{$t('parking.index.availableCoupons')}}
            </view>
          </view>
          <view class="coupon-list">
            <view
              v-for="(coupon, index) in displayCoupons"
              :key="index"
              class="coupon-item"
              :class="{'selected': selectedCoupon === coupon.raw}"
              @click="selectCoupon(coupon.raw)"
            >
              <view class="coupon-left">
                <text class="coupon-amount">¥{{coupon.amount}}</text>
                <text class="coupon-condition">{{$t('parking.index.couponCondition', {min: coupon.min})}}</text>
              </view>
              <view class="coupon-right">
                <text class="coupon-name">{{coupon.name}}</text>
                <text class="coupon-time">{{coupon.time}}</text>
              </view>
            </view>
          </view>
        </view>

        <view class="info-item highlight">
          <text class="label">{{$t('parking.index.payableAmount')}}</text>
          <view class="price-info">
            <text class="original-price" v-if="selectedCoupon">¥{{originalPrice}}</text>
            <text class="value">¥{{payAmount.toFixed(2)}}</text>
          </view>
        </view>
      </view>

      <view class="action-btn" @click="goPay">{{$t('parking.index.payNow')}}</view>
    </view>

    <!-- 加载状态 -->
    <view class="loading-mask" v-if="loading">
      <view class="loading-content">
        <view class="loading-icon"></view>
        <text class="loading-text">{{$t('parking.index.querying')}}</text>
      </view>
    </view>

    <!-- 车牌号输入键盘 -->
    <view class="keyboard-container" v-if="showKeyboard">
      <view class="keyboard-mask" @click="hideCarKeyboard"></view>

      <view class="keyboard-content">
        <!-- 省份选择键盘 -->
        <view class="province-keyboard" v-if="inputType === 'province'">
          <view class="keyboard-title">{{$t('parking.index.selectProvince')}}</view>
          <view class="province-list">
            <view
              v-for="(province, index) in provinces"
              :key="index"
              class="province-item"
              @click="clickProvince(province)"
            >
              {{province}}
            </view>
          </view>
        </view>

        <!-- 字母数字键盘 -->
        <view class="number-keyboard" v-else>
          <view class="keyboard-title">{{$t('parking.index.enterLicensePlate')}}</view>

          <view class="keyboard-rows">
            <view class="keyboard-row" v-for="(row, rowIndex) in keyboards" :key="rowIndex">
              <view
                v-for="(key, keyIndex) in row"
                :key="keyIndex"
                class="key-item"
                @click="clickKey(key)"
              >
                {{key}}
              </view>
            </view>

            <view class="keyboard-row">
              <view class="key-item function" @click="deleteKey">{{$t('parking.index.delete')}}</view>
              <view class="key-item function" @click="hideCarKeyboard">{{$t('parking.index.close')}}</view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<style scoped lang="scss">
.parking-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 页面标题 */
.page-header {
  margin-bottom: 30rpx;

  .title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
  }
}

/* 通用区块样式 */
.section-title {
  font-size: 30rpx;
  color: #666;
  margin-bottom: 20rpx;
  padding: 0 30rpx;
}

/* 合并的卡片容器 */
.combined-card {
  margin: 30rpx;
  background: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

/* 积分卡片 */
.points-card {
  padding: 24rpx 30rpx;
  border-radius: 16rpx 16rpx 0 0;
  background-image: url("https://wzws.wanshanlundiao.cn/upload/img/20250516/202505161112024929.png");
  background-repeat: no-repeat;
  background-size: cover;
}

.points-row {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .points-left {
    font-size: 28rpx;
    color: #D9C092;
    display: flex;
    align-items: center;

    image{
      width: 42rpx;
      height: 36rpx;
      margin-right: 10rpx;
    }

    .points-value {
      color: #FFAC15;
      font-weight: bold;
      margin-left: 8rpx;
    }
  }

  .points-btn {
    color: #FFAC15;
    font-size: 26rpx;
    border-radius: 30rpx;
    padding: 10rpx 12rpx 10rpx 32rpx;
    font-weight: bold;
  }
}

/* 车牌输入区域 */
.car-number-section {
  padding: 30rpx;

  .car-number-input-grid {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20rpx;

    .input-box {
      width: 70rpx;
      height: 100rpx;
      background-color: #fff;
      border-radius: 8rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 36rpx;
      font-weight: 500;
      color: #333;
      border: 2rpx solid #e0e0e0;
      position: relative;

      &.active {
        border-color: #4794FF;
      }

      &.filled {
        border-color: #e0e0e0;
        background-color: #fff;
      }

      &.new-energy-box {
        border-color: #3ec16d !important;
      }

      .cursor {
        width: 2rpx;
        height: 40rpx;
        background-color: #4794FF;
        animation: blink 1s infinite;
      }

      .new-energy-tag {
        position: absolute;
        left: 50%;
        top: 60%;
        transform: translate(-50%, -50%);
        display: flex;
        flex-direction: column;
        align-items: center;

        .energy-text {
          color: #3ec16d;
          font-size: 32rpx;
          font-weight: bold;
          margin-top: 0;
        }
      }
    }
  }

  .query-btn {
    height: 90rpx;
    background-color: #e0e0e0;
    border-radius: 45rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 32rpx;
    color: #666;
    font-weight: 500;
    margin-top: 30rpx;

    &.active {
      background: linear-gradient(135deg, #4794FF 0%, #2C6BEA 100%);
      color: #fff;
    }
  }
}

@keyframes blink {
  0%, 100% { opacity: 1; }
  50% { opacity: 0; }
}

/* 停车信息区域 */
.parking-info-section {
  background-color: #fff;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  margin: 0 30rpx 30rpx;

  .info-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    background-color: #f8f8f8;

    .car-info {
      .car-number {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
        margin-right: 20rpx;
      }

      .parking-lot {
        font-size: 26rpx;
        color: #666;
      }
    }

    .edit-btn {
      font-size: 26rpx;
      color: #4794FF;
    }
  }

  .info-content {
    padding: 20rpx 30rpx;

    .info-item {
      display: flex;
      justify-content: space-between;
      padding: 20rpx 0;
      border-bottom: 1px solid #f0f0f0;

      &:last-child {
        border-bottom: none;
      }

      &.highlight {
        .label, .value {
          font-weight: bold;
          color: #ff5233;
        }

        .value {
          font-size: 36rpx;
        }
      }

      .label {
        font-size: 28rpx;
        color: #666;
      }

      .value {
        font-size: 28rpx;
        color: #333;
      }
    }
  }

  .action-btn {
    height: 90rpx;
    background: linear-gradient(135deg, #4794FF 0%, #2C6BEA 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 32rpx;
    color: #fff;
    font-weight: 500;
  }
}

/* 加载遮罩 */
.loading-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;

  .loading-content {
    display: flex;
    flex-direction: column;
    align-items: center;

    .loading-icon {
      width: 60rpx;
      height: 60rpx;
      border: 6rpx solid #4794FF;
      border-top-color: transparent;
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin-bottom: 20rpx;
    }

    .loading-text {
      font-size: 28rpx;
      color: #666;
    }
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 车牌键盘 */
.keyboard-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1000;

  .keyboard-mask {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
  }

  .keyboard-content {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #fff;
    border-radius: 20rpx 20rpx 0 0;
    padding: 30rpx;
    transform: translateY(0);
    transition: transform 0.3s;

    .keyboard-title {
      text-align: center;
      font-size: 30rpx;
      color: #333;
      margin-bottom: 30rpx;
    }
  }

  /* 省份键盘 */
  .province-list {
    display: flex;
    flex-wrap: wrap;

    .province-item {
      width: calc(100% / 9);
      height: 80rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 32rpx;
      color: #333;
      margin-bottom: 20rpx;

      &:active {
        background-color: #f0f0f0;
        border-radius: 8rpx;
      }
    }
  }

  /* 数字字母键盘 */
  .keyboard-rows {
    .keyboard-row {
      display: flex;
      justify-content: center;
      margin-bottom: 20rpx;

      .key-item {
        width: 70rpx;
        height: 80rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 32rpx;
        color: #333;
        background-color: #f5f5f5;
        border-radius: 8rpx;
        margin: 0 5rpx;

        &:active {
          background-color: #e0e0e0;
        }

        &.function {
          width: 120rpx;
          background-color: #4794FF;
          color: #fff;
        }
      }
    }
  }
}

// 优惠券样式
.coupon-section {
  margin: 20rpx 0;

  .coupon-header {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;

    .label {
      font-size: 28rpx;
      color: #666;
    }

    .coupon-status {
      flex: 1;
      text-align: right;
      font-size: 24rpx;
      color: #498FFF;
    }
  }

  .coupon-list {
    .coupon-item {
      display: flex;
      align-items: center;
      background: #FFF;
      border: 2rpx solid #E5E5E5;
      border-radius: 8rpx;
      padding: 20rpx;
      margin-bottom: 20rpx;

      &.selected {
        border-color: #498FFF;
        background: rgba(73, 143, 255, 0.05);
      }

      .coupon-left {
        width: 160rpx;
        text-align: center;
        border-right: 2rpx dashed #E5E5E5;
        padding-right: 20rpx;

        .coupon-amount {
          font-size: 36rpx;
          color: #FF4B31;
          font-weight: bold;
          display: block;
        }

        .coupon-condition {
          font-size: 22rpx;
          color: #999;
          margin-top: 8rpx;
          display: block;
        }
      }

      .coupon-right {
        flex: 1;
        padding-left: 20rpx;

        .coupon-name {
          font-size: 28rpx;
          color: #333;
          display: block;
        }

        .coupon-time {
          font-size: 24rpx;
          color: #999;
          margin-top: 8rpx;
          display: block;
        }
      }
    }
  }
}

.price-info {
  display: flex;
  align-items: baseline;

  .original-price {
    font-size: 24rpx;
    color: #999;
    text-decoration: line-through;
    margin-right: 10rpx;
  }

  .value {
    font-size: 36rpx;
    color: #ff5233;
    font-weight: bold;
  }
}
</style>
